package com.nb.controller;

import com.nb.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/common")
public class UpDownLoadController {

    @Value("${reggie.path}")
    private String basePath;

    //上传
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile  file){

        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取原始文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件同名被覆盖
        String newFileName = UUID.randomUUID().toString()+ suffix;

        //判断上传文件存储的目录是否存在，如果没有就新建一个
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //转存上传的文件到指定目录
        try {
            file.transferTo( new File(basePath+newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(newFileName);
    }

    //下载
    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response){

        try {
            //从硬盘中读取文件
            FileInputStream fis = new FileInputStream(new File(basePath+name));
            //将文件写入到浏览器
            OutputStream out = response.getOutputStream();
            //设置格式
            response.setContentType("image/jpeg");

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) !=-1) {
                out.write(buffer,0,len);
                out.flush();
            }
            fis.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
